package com.bdzl.auth.util;

import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.bdzl.auth.common.utils.DateUtils;
import com.bdzl.pub.entity.sys.MobileCodeDO;

import java.util.List;


public class SmsUtil {

    /**
     * TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找，上方申请的)
     * #AccessKey ID
     * aliyun_oss_accesskey:LTAIb59vUeT2OABK
     * #AccessKey Secret
     * aliyun_oss_accesskeysecret:o2OqTi5RphmCv42U2H05GLdupXXMWE
     */
    static final String accessKeyId = "LTAIb59vUeT2OABK";
    static final String accessKeySecret = "o2OqTi5RphmCv42U2H05GLdupXXMWE";

    /**
     * @Author Zhn
     * @Description //TODO 修改密码专用
     * @Date 10:44 2021/5/19
     * @Param [phone]
     * @return java.lang.String
     **/        
    public static MobileCodeDO sendSms(MobileCodeDO mobileCodeDO, String phone, String id) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("北斗智联");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(id);
        String verificationCode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    	//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        if (id.equals("SMS_133261393")){
            request.setTemplateParam("{\"captcha\":\""+verificationCode+"\"}");
        }else {
            request.setTemplateParam("{\"code\":\""+verificationCode+"\"}");
        }
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId(verificationCode);
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode().equals("OK")){
                //睡一秒
                Thread.sleep(1000);
                //调用明细接口
                mobileCodeDO.setMcMsg(createClient(phone, sendSmsResponse.getBizId(), DateUtils.now1()));
                mobileCodeDO.setMcCode(verificationCode);
                return mobileCodeDO;
            }
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        mobileCodeDO.setMcCode("OFF");
        return mobileCodeDO;
    }



    /**
     * @Author Zhn
     * @Description //TODO 获取刚刚发送的短信详情
     * @Date 17:10 2021/5/22
     * @Param [phone, BizId, time]
     * @return java.lang.String
     **/
    public static String createClient(String phone,String BizId,String time) throws Exception {
        //设置超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //云通信产品-短信API服务产品名称（短信产品名固定，无需修改）
        final String product = "Dysmsapi";
        //云通信产品-短信API服务产品域名（接口地址固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";
        //初始化ascClient
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber(phone);
        //可选-调用发送短信接口时返回的BizId
        request.setBizId(BizId);
        //必填-短信发送的日期 支持30天内记录查询（可查其中一天的发送数据），格式yyyyMMdd
        request.setSendDate(time);
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);
        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);
        //获取返回结果
        if(querySendDetailsResponse.getCode() != null && querySendDetailsResponse.getCode().equals("OK")){
            List<QuerySendDetailsResponse.SmsSendDetailDTO> smsSendDetailDTOs = querySendDetailsResponse.getSmsSendDetailDTOs();
            //代表请求成功
            for (QuerySendDetailsResponse.SmsSendDetailDTO item:smsSendDetailDTOs) {
                String content = item.getContent();
                //返回明细
                return content;
            }
        }
        return "短信获取失败!";
    }


}
